﻿'use strict';

var redis = require("../utils/redis");
var db = require("../utils/db");

var constant = require('../utils/constant');
var logger = require('../utils/log');

var rooms = {};
var totalRooms = 0;

var userLocateRoom = {};

exports.init = function() {
    //启动时 获取 redis 遗留的房间信息
    redis.getAllRoomInfo(function (list) {
        if (list == null) return;

        list.forEach(function (roomInfo, index) {

            //获取 redis 遗留的房间游戏数据
            redis.getRoomGameResults(roomInfo.roomNo, function (result) {
                if (result == null) return;

                var statistic = JSON.parse(result);
                logger.debug('statistic', statistic);

                var userIds = [];
                for (var userId in statistic) {
                    userIds.push(userId);
                }
                //获取 redis 遗留的房间的玩家信息
                redis.getSomeUserInfo(userIds, function (list) {
                    var users = {};
                    var temp = null;

                    list.forEach(function (userInfo, index) {
                        temp = {};
                        temp.name = userInfo.name;
                        temp.headimg = userInfo.headimg;
                        temp.score = statistic[userInfo.userId].score;
                        users[userInfo.userId] = temp;
                    });
                    var plays_info = JSON.stringify(users);

                    //db缓存游戏结果
                    db.setUsersRoomRecord(userIds, roomInfo.roomId, null);
                    db.updateRoomResult(roomInfo, plays_info, result, null);

                    //删除用户的房间号
                    redis.removeUserAllRoomNo(userIds, roomInfo.roomNo);
                    //删除房间信息 和 游戏统计数据
                    redis.removeRoomAndGameResult(roomInfo.roomNo, null);
                });
            });
        });
    });
};

//创建房间
exports.createRoom = function(userId, conf){
    var roomNo = generateRoomNo();
    if (roomNo == "") return constant.CODE_ERROR;

    conf = JSON.parse(conf);
    var room = generateRoomInfo(userId, conf, roomNo);

    rooms[roomNo] = room;
    totalRooms++;
    exports.enterRoom(userId, roomNo);

    var rt = {
        roomId:room.roomId,
        roomNo:room.roomNo,
        createTime:room.createTime,
    };
    return rt;
};

//进入房间 并未坐下
exports.enterRoom = function(userId, roomNo){
    var room = rooms[roomNo];
    if (room == null) return constant.CODE_ROOM_NULL_ERROR;

    //麻将以及斗地主 不允许观战
    if (room.type > 30) {
        if (room.users.length >= room.conf.renshu) {
            var exist = false;
            for (var tempId in room.userInfos) {
                if (tempId == userId) {
                    exist = true;
                    break;
                }
            }
            if (exist) {
                return constant.CODE_SUCCESS;
            } else {
                return constant.CODE_ROOM_ENOUGT_ERROR;
            }
        }
    }

    room.users.push(userId);
    userLocateRoom[userId] = roomNo;

    return constant.CODE_SUCCESS;
};

//坐下
exports.sitRoom = function (userId, roomNo, userInfo) {
    var room = rooms[roomNo];
    if (room == null) return constant.CODE_ERROR;

    var index = -1;
    for (var i = 0; i < 4; i++) {
        var seat = room.seats[i];
        if (seat == null) { //seat不存在
            index = i;
            break;
        }
    }
    if (index > -1) { //seat不存在
        userInfo.index = index;
        userInfo.online = true;

        room.seats[index] = userInfo;
        room.userInfos[userId] = userInfo;

        //进入房间 修改redis 房间人数
        redis.incrRoomMembers(roomNo, 1);
    }
    return constant.CODE_SUCCESS;
};

//暂时离开房间
exports.onlineRoom = function(userId, roomNo, index){
    var room = rooms[roomNo];
    if (room == null || index == null) return constant.CODE_ERROR;

    var userInfo = room.seats[index];
    userInfo.online = false;

    return constant.CODE_SUCCESS;
};

//回到房间
exports.offlineRoom = function(userId, roomNo, index){
    var room = rooms[roomNo];
    if (room == null || index == null) return constant.CODE_ERROR;

    var userInfo = room.seats[index];
    userInfo.online = true;

    return constant.CODE_SUCCESS;
};

//退出房间
exports.exitRoom = function(userId, roomNo, index){
    var room = rooms[roomNo];
    if (room == null || index == null) return constant.CODE_ERROR;

    room.seats[index] = null;
    room.userInfos[userId] = null;

    index = room.users.indexOf(userId);
    if (index != -1) return constant.CODE_ERROR;
    room.users.splice(index, 1);

    delete userLocateRoom[userId];

    //退出房间 修改redis 房间人数
    redis.incrRoomMembers(roomNo, -1);

    return constant.CODE_SUCCESS;
};

//解散 或者 游戏自动结束
exports.closeRoom = function(userId, roomNo){
	var room = rooms[roomNo];
	if (room == null) return constant.CODE_ERROR;
    if (!exports.isCreator(roomNo, userId)) return constant.CODE_ERROR;

    //删除玩家相关location
    room.users.forEach(function (playerId) {
        delete userLocateRoom[playerId];
    });

    //删除用户的房间号
    redis.removeUserAllRoomNo(room.users, roomNo);
    //删除房间信息 和 游戏统计数据
    redis.removeRoomAndGameResult(roomNo, null);

    //删除房间信息
	delete rooms[roomNo];
	totalRooms--;
};

exports.saveRoomInfo = function(roomNo) {
    var room = rooms[roomNo];
    if (room == null) return constant.CODE_ERROR;

    var users = {};
    var temp = null;
    var userIds = [];
    for (var userId in room.userInfos) {
        var userInfo = room.userInfos[userId];
        temp = {};
        temp.name = userInfo.name;
        temp.headimg = userInfo.headimg;
        temp.score = room.statistics[userId].score;

        users[userId] = temp;
        userIds.push(userId);
    }
    var plays_info = JSON.stringify(users);
    var result = JSON.stringify(room.statistics);

    //db缓存游戏结果
    db.setUsersRoomRecord(userIds, room.roomId, null);
    db.updateRoomResult(room, plays_info, result,  null);
};

exports.isCreator = function(roomNo, userId){
    var room = rooms[roomNo];
    if (room == null) return false;

    return room.creator == userId;
};

exports.getTotalRooms = function(){
	return totalRooms;
};

exports.getRoomByRoomNo = function(roomNo){
	return rooms[roomNo];
};

exports.getRoomByUserId = function(userId){
	var roomNo = userLocateRoom[userId];
	if (roomNo != null) return rooms[roomNo];
	return null;
};

function generateRoomInfo(userId, conf, roomNo){
    var createTime = Date.now();
    var roomId = userId + createTime;
    var room = {
        roomId:roomId,
        roomNo:roomNo,
        conf:conf,
        type:conf.type,
        creator:userId,

        seats:{},//玩家{index-userInfo}
        userInfos:{},//玩家{userId-userInfo}
        users:[],//玩家+旁观者 麻将以及斗地主 不允许观战
        results:[],
        statistics:{},//统计数据
        createTime:createTime,
    };
    return room;
};

function generateRoomNo(){
    var roomNo = 0;
    for (var i = 0; i < 20; i++) {
        for(var j = 5; j > -1; --j){
            roomNo += Math.floor(Math.random()*10) * Math.pow(10, j);
        }
        if (roomNo < 100000) {
            roomNo += 100000;
        }
        roomNo = String(roomNo);
        logger.debug('generateRoomNo', roomNo);
        if (rooms[roomNo] == null) {
            break;
        } else {
            roomNo = 0;
        }
    }
    return roomNo;
};

